//
//  HomeTableViewController.swift
//  MyWeibo
//
//  Created by 余丽丽 on 15/10/8.
//  Copyright © 2015年 余丽丽. All rights reserved.
//

import UIKit
/// 返回大于since_id的微博,即最新的
var since_id = 0
/// 返回小于max_id的微博,即旧的
var max_id = 0

//是否是 Modal 展现的标记
var isPresented = false
var PushfromView = UIImageView()
var PushfromRect = CGRectZero

var PopFromView = UIImageView()
var PopToViewSuper:StatusPictureView?
//更新数据枚举
enum refreshEnum:String{
    case Normal = "Normal"
    case pushRefresh = "pushRefresh"
    case pullRefresh = "pullRefresh"
    
}


class HomeTableViewController: BaseTableViewController {

    
    
    
    var statues:[Status]?{
        didSet{
            tableView.reloadData()
        }
    
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !UserAccount.userLogon {
            visitorView?.setupViewInfo(true, imageName:"visitordiscover_feed_image_smallicon",message: "关注一些人，回这里看看有什么惊喜")
            return
        }
        
        //注册通知  处理照片查看
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectPicture:", name: statusSelectImgNotification, object: nil)
           
            prepareTableView()
            loadData(refreshEnum.Normal)
        

    }

    
    deinit{
        //注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 查看照片
    @objc private func selectPicture(n:NSNotification){
    // TODO:| 转场动画
        print(n)
        guard let urls = n.userInfo![statusSelectImgURLKey] as? [AnyObject] else{
        
            print("大图URL数组不存在!!")
            return
        }
        
        guard let index = n.userInfo![statusSelectImgIndexpathKey] as? NSIndexPath else{
        
            print("index不存在!")
            return
        }
        
        let vc = PhotoBrowerViewController(urls: urls, index: index.item)
        // 设置Model转场代理
        vc.transitioningDelegate = self
        // 2. 指定Modal转场模式 － 自定义,要实现自定义,一定要使用转场代理
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        
        //modal出来的专场动画默认是从下到上的
        presentViewController(vc, animated: true, completion: nil)
    
    }
    
    /// 准备表格视图
    private func prepareTableView() {
        //注册cell
      tableView.registerClass(StatusCell.self, forCellReuseIdentifier: StatusCellIdentifier.NormalCell.rawValue)
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: StatusCellIdentifier.ForwardCell.rawValue)
        
        //设置预估行高
        tableView.estimatedRowHeight = 200
        //自动行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        // TODO:| 自定义刷新控件
        refreshControl = UIRefreshControl()
        //给刷新按钮添加事件,下拉刷新会显示菊花并执行监听方法,下拉刷新无效
        refreshControl?.addTarget(self, action: "pullRefreshData", forControlEvents: UIControlEvents.ValueChanged)
    }
    
    
    @objc private func pullRefreshData(){
    
        //下拉刷新
        loadData(refreshEnum.pullRefresh)
        refreshControl?.endRefreshing()
    }
    
    
    @objc private func pushRefreshData(){
        //上推刷新
        loadData(refreshEnum.pushRefresh)
        
    }
    
    
    /// 加载数据并刷新
      func loadData(refresh: refreshEnum) {
        
        //下拉刷新
        since_id = (refresh == refreshEnum.pullRefresh) ? (statues?.first?.id ?? 0) : 0
        //上推刷新
        max_id = (refresh == refreshEnum.pushRefresh) ? (statues?.last?.id ?? 0) : 0
        
        Status.loadStatus { [weak self](dataList, error) -> () in
            if error != nil{
                print(error)
                return
            }
            
            let count = dataList?.count ?? 0
            
            if count == 0 {
                print("没有新数据")
                return
            }
            
            print("刷新了数据条数:\(count))")
            
            switch refresh {
                
                case refreshEnum.pullRefresh:
                    self!.statues! = dataList! + self!.statues!
                
                
                case refreshEnum.pushRefresh:
                    self!.statues! = self!.statues! + dataList!
                
                default:
                    self!.statues = dataList
                
            }
            
        }
        
       
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
       
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return statues?.count ?? 0
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cellstatus = statues![indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellID(cellstatus) , forIndexPath: indexPath) as! StatusCell
        cell.status = cellstatus
        if indexPath.item == (statues?.count)! - 1 {
            pushRefreshData()
            
        }
        return cell
    }
    
   }



///  自定义转场动画的协议
extension HomeTableViewController: UIViewControllerTransitioningDelegate{

//返回提供转场动画的遵守 `UIViewControllerAnimatedTransitioning` 协议的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{
        isPresented = true
        return self
    }
    
    /// 返回提供解除转场的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{
        isPresented = false
        return self
    }
    
    //Present动画的百分比
//    func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?{}
   
    //Dismiss动画的百分比
//    func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?{}
    

//    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController?{}

}


///  自定义转场动画
extension HomeTableViewController: UIViewControllerAnimatedTransitioning{
    
    // 返回转场动画的时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval{
        return 0.6
    }
    // This method can only  be a nop if the transition is interactive and not a percentDriven interactive transition.
    // 转场动画的具体内容
    /**
        transitionContext 提供了转场动画需要的元素
        
        completeTransition(true) 动画结束后必须调用的
        containerView() 容器视图
        
        viewForKey      获取到转场的视图
    
    备注:
        自定义转场动画的时候,需要准备两个动画,一个push一个pop,最好用一个标识符来区分
    准备转场动画的过程:
    1.准备fromView,fromRect,toView,toRect(我的经验是,谁modal谁准备from,to可以根据ket来)
    2.使用UIView的动画方法,设置动画时长和fromView的frame的最终值
    3.动画结束后删除动画视图,如果是push一定要将toview添加到转场动画的视图容器中,最后一定要transitionContext.completeTransition(true)
    */
    func animateTransition(transitionContext: UIViewControllerContextTransitioning){
        //TODO:|有待优化,图片大小适应
        if isPresented{
        // 转场
        //modal向谁?
            let PushtoView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            let PushtoRect = UIScreen.mainScreen().bounds
            
            //将动画的添加到目标视图中
            transitionContext.containerView()?.addSubview(PushfromView)
            //设置起始位置
            PushfromView.frame = PushfromRect
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            
                //动画运动到指定的位置
                PushfromView.frame = PushtoRect

                }, completion: { (_) -> Void in
                
                    //删除动画
                    PushfromView.removeFromSuperview()
                    transitionContext.containerView()?.addSubview(PushtoView)
                    //completeTransition(true) 动画结束后必须调用的
                    transitionContext.completeTransition(true)
                    
            })
            
            return
         
        }else{
            
         // 根据当前cell的indexpath获取pictureview中相应indexpath的cell的rect,作为pop转场动画的PoptoRect
            let popFromVc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as!PhotoBrowerViewController
            let index = popFromVc.currentIndexPath()
            let PopToRect = PopToViewSuper?.cellRectAtIndexPath(index)
            
            transitionContext.containerView()?.addSubview(PopFromView)
            
            PopFromView.frame = UIScreen.mainScreen().bounds
          
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                PopFromView.frame = PopToRect!
                popFromVc.view.alpha = 0
                }, completion: { (_) -> Void in
                    //删除动画
                    PopFromView.removeFromSuperview()
                    // 解除转场时，会把 容器视图以及内部的内容一起销毁
                    transitionContext.completeTransition(true)
                    
            })
            
            
            
        }
    }
    
    // This is a convenience and if implemented will be invoked by the system when the transition context's completeTransition: method is invoked.
    func animationEnded(transitionCompleted: Bool){}
    
}

